<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="query.phone" class="filter-item w-200" size="medium" placeholder="手机号码" clearable>
      </el-input>
      <el-select v-model="query.school_id" class="filter-item w-200" size="medium" placeholder="学校" clearable>
      <el-option v-for="item,index in schools" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-button icon="el-icon-search" size="medium" class="filter-item" @click="fetchList">搜 索</el-button>
      <el-button type="primary" size="medium" icon="el-icon-plus" class="filter-item" style="float:right" @click="handleShowAddForm" v-permission="'school-admins.store'">新增</el-button>
    </div>
    <el-table :data="data" border stripe v-loading="visible.tableLoading" >
      <el-table-column label="id" prop="id" width="100px" align="center">
      </el-table-column>
      <el-table-column label="手机号码/账号" prop="phone" align="center">
      </el-table-column>
      <el-table-column label="姓名" prop="name" align="center">
      </el-table-column>
      <el-table-column label="学校" prop="school.name" align="center">
      </el-table-column>
      <el-table-column label="权限组" align="center">
        <template slot-scope="scope">
          {{rolesToString(scope.row.roles)}}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" align="center">
        <span slot-scope="{row}">
          {{row.status === 1? "启用":"禁用"}}
        </span>
      </el-table-column>
      <el-table-column label="超级管理员" prop="is_super" align="center">
        <span slot-scope="{row}">
          {{row.is_super === 1? "是":"否"}}
        </span>
      </el-table-column>
      <el-table-column label="创建时间" prop="created_at" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button icon="el-icon-edit" size="mini" type="primary" @click="handleShowEdit(row)" v-permission="'school-admins.update'">编辑</el-button>
          <el-button icon="el-icon-refresh" size="mini" type="danger" @click="handleResetPassword(row)" v-permission="'school-admins.refresh'">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="query.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog :visible.sync="visible.form" :title="formTitle" width="700px">
      <el-form :model="form" label-width="120px" :rules="rules" ref="form" >
        <el-form-item prop="name" label="所有人姓名">
          <el-input v-model="form.name" :disabled="formType === 'edit'"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机">
          <el-input v-model="form.phone" :disabled="formType === 'edit'"></el-input>
        </el-form-item>
        <el-form-item label="学校" prop="school_id">
          <el-select v-model="form.school_id" @change="changeSchool" placeholder="请选择学校" style="width: 100%">
            <el-option
                    v-for="school in schools"
                    :key="school.id"
                    :label="school.name"
                    :value="school.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="password" label="登录密码" v-if="formType === 'add'">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item porp="status" label="启用">
          <el-switch v-model="form.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" :disabled="is_super"></el-switch>
        </el-form-item>
        <el-form-item porp="is_super" label="超级管理员">
          <el-switch v-model="form.is_super" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" :disabled="is_super"></el-switch>
        </el-form-item>
        <el-form-item v-if="!is_super" label="权限角色" prop="roles">
          <el-select v-model="form.roles" multiple placeholder="请选择" style="width: 100%">
            <el-option
                    v-for="role in roles"
                    :key="role.id"
                    :label="role.label"
                    :value="role.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible.form = false">取 消</el-button>
        <el-button type="primary" @click="handleForm" :loading="visible.buttonLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { fetchSchoolAdmin, addSchoolAdmin, updateSchoolAdmin, showSchoolAdminsAndRoles, refreshSchoolAdmin } from '@/api/school'
  import { isPhoneAvailable } from '@/utils/validate'
  import { fetchData } from '@/api/data'
  export default {
    name: 'school-admin',
    data() {
      const validPhone = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入电话号码'))
        } else if (!isPhoneAvailable(value)) {
          callback(new Error('请输入正确的11位手机号码'))
        } else {
          callback()
        }
      }
      return {
        is_super: false,
        query: {
          school_id: '',
          phone: '',
          page: 1,
          size: 10
        },
        total: 0,
        visible: {
          tableLoading: false,
          form: false,
          buttonLoading: false
        },
        form: {
          phone: '',
          password: null,
          is_super: 0,
          status: 1,
          name: '',
          roles: [],
          school_id: ''
        },
        formType: 'add',
        formTitle: '新增学校管理员',
        updateRow: {},
        data: [],
        schools: [],
        roles: [],
        rules: {
          name: { required: true, message: '请输入所有人姓名', trigger: ['blur', 'change'] },
          phone: { required: true, trigger: ['blur', 'change'], validator: validPhone },
          password: { required: true, message: '请输入登录密码', trigger: ['blur', 'change'] },
          school_id: { required: true, message: '请选择学校', trigger: ['blur', 'change'] }
        }
      }
    },
    methods: {
      // 切换学校时，若该学校下无管理员，则当前默认添加超级管理员；若有则刷新该学校下的权限角色
      changeSchool() {
        showSchoolAdminsAndRoles(this.form.school_id).then(res => {
          this.roles = res.roles
          // 当前选中学校下没有管理员，则默认添加超级管理员
          this.is_super = (res.admins.length <= 0)
          if (this.is_super) {
            this.form.status = 1
            this.form.is_super = 1
            this.form.roles = []
          }
        })
      },
      rolesToString(roles) {
        return roles.reduce((carry, role, index) => {
          if (index === 0) {
            return role.label
          }
          return role.label + '，' + carry
        }, '')
      },
      handleResetPassword(row) {
        this.$prompt('请输入新密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[a-zA-Z0-9]{6,20}$/,
          inputErrorMessage: '密码长度必须在6-20之间'
        }).then(({ value }) => {
          refreshSchoolAdmin(row.id, { password: value }).then(res => {
            this.$message.success('重置密码成功')
            this.visible.form = false
          }).catch(err => {
            this.$handleNotFound(err, '管理员不存在')
          })
        })
      },
      handleSizeChange(size) {
        this.query.size = size
        this.fetchList(true)
      },
      handleCurrentChange(page) {
        this.query.page = page
        this.fetchList()
      },
      handleForm() {
        if (this.formType === 'add') {
          this.visible.buttonLoading = true
          this.$refs['form'].validate(valid => {
            if (valid) {
              addSchoolAdmin(this.form).then(res => {
                this.$message.success('新增成功')
                this.fetchList()
                this.visible.form = false
              }).catch(err => {
                this.$handleNotFound(err)
              })
            }
            this.visible.buttonLoading = false
          }).catch(() => {
            this.visible.buttonLoading = false
          })
        } else if (this.formType === 'edit') {
          updateSchoolAdmin(this.updateRow.id, this.form).then(res => {
            this.$message.success('编辑成功')
            Object.assign(this.updateRow, res.data)
            this.fetchList()
            this.visible.form = false
            this.visible.buttonLoading = false
          }).catch(err => {
            this.$handleNotFound(err, '学校管理员不存在')
            this.visible.buttonLoading = false
          })
        }
      },
      // 重置表单验证
      resetForm(formName) {
        // 第一次新增数据时为空对象undefined
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
      },
      handleShowAddForm() {
        this.resetForm('form')
        this.formTitle = '新增学校管理员'
        this.formType = 'add'
        Object.assign(this.form, this.$options.data().form)
        this.visible.form = true
        this.is_super = false
        this.roles = []
      },
      handleShowEdit(row) {
        this.formTitle = '编辑学校管理员'
        Object.existAssign(this.form, row)
        this.formType = 'edit'
        this.form.roles = []
        for (const role of row.roles) {
          this.form.roles.push(role.id)
        }
        this.updateRow = row
        this.visible.form = true
        this.changeSchool()
      },
      fetchList(reset = false) {
        this.visible.tableLoading = true
        if (reset) {
          this.page = 1
        }
        fetchSchoolAdmin(this.query).then(res => {
          this.data = res.data
          this.total = res.meta.total
          this.visible.tableLoading = false
        })
      }
    },
    created() {
      this.fetchList()
      fetchData({ sources: ['schools'] }).then(res => {
        this.schools = res.schools
      })
    }
  }
</script>

<style scoped>

</style>
